#include "mainwindow.h"
#include "arkanoid.h"
#include <QMessageBox>
#include <QBuffer>
#include <QProcess>

QString mainWindow::version = "1.00";

mainWindow::mainWindow(QWidget *parent, Qt::WFlags f)
	:QMainWindow(parent, f)
{
	setupUi(this);
	statusbar->setGeometry(statusbar->pos().x(), statusbar->pos().y(), statusbar->width(), 25);
	setMinimumSize(800, 600 + menubar->height() + statusbar->height());
	setMaximumSize(minimumSize());
        gbd = new Arkanoid(this);
	gbd->setMinimumSize(800, 600);
	gbd->setMaximumSize(gbd->minimumSize());
	gbd->setGeometry(0, menubar->height(), 800, 600);
	actionPause->setEnabled(false);
	actionStop->setEnabled(false);
	actionESave->setEnabled(false);
	actionESaveAs->setEnabled(false);
	actionEFinish->setEnabled(false);
	statusbar->setSizeGripEnabled(false);
	blocks = new QLabel();
	lifes = new QLabel();
	score = new QLabel();
	blocks->setFrameStyle(QFrame::Panel | QFrame::Sunken);
	lifes->setFrameStyle(QFrame::Panel | QFrame::Sunken);
	score->setFrameStyle(QFrame::Panel | QFrame::Sunken);
	statusbar->addWidget(blocks);
	statusbar->addWidget(lifes);
	statusbar->addWidget(score);
	colors = new QToolBar();
	colors->setEnabled(false);
	colors->hide();
	colors->setWindowTitle(QString::fromUtf8("Цвет нового блока по умолчанию"));
	colors->setToolTip(colors->windowTitle());
	colors->setIconSize(QSize(16, 16));
	colors->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
	addToolBar(Qt::BottomToolBarArea, colors);
	gbd->fillColors();
	addCompleted("Miniclip");
	cntn = "";
	createLevelsMenu();
	connect(gbd, SIGNAL(setPauseText()), SLOT(setPauseText()));
	connect(gbd, SIGNAL(gameStoped()), SLOT(onStop()));
	connect(gbd, SIGNAL(blocksChanged(int)), SLOT(setBlocksCount(int)));
	connect(gbd, SIGNAL(lifesChanged(int)), SLOT(setLifesCount(int)));
	connect(gbd, SIGNAL(scoreChanged(int)), SLOT(setScoreCount(int)));
	connect(gbd, SIGNAL(win()), SLOT(win()));
}

mainWindow::~mainWindow()
{
	delete gbd;
}

void mainWindow::on_actionNew_triggered()
{
	campaign = true;
        beginLevel(":Miniclip");
}

void mainWindow::on_actionPause_triggered()
{
	gbd->pauseGame();
	if (gbd->isPaused())
		actionPause->setText(QString::fromUtf8("Продолжить"));
	else
		actionPause->setText(QString::fromUtf8("Пауза"));
}

void mainWindow::on_actionStop_triggered()
{
	gbd->stopGame();
	onStop();
}

void mainWindow::on_actionOwn_triggered()
{
	campaign = false;
	QString file = getLevelFN();
	if (!file.isNull())
                beginLevel((QFileInfo(file).baseName()));
}

void mainWindow::beginLevel(QString lvl, int lifes_c, int score_c)
{
	if (gbd->isPaused())
		gbd->pauseGame();
	if (gbd->isEnabled())
		gbd->stopGame();
	gbd->loadLevel(lvl, lifes_c, score_c);
	actionPause->setEnabled(true);
	actionStop->setEnabled(true);
}

void mainWindow::beginEdit(QString lvl)
{
	menu->setEnabled(false);
	actionESave->setEnabled(true);
	actionESaveAs->setEnabled(true);
	actionEFinish->setEnabled(true);
	gbd->setEditmode(true);
	on_actionStop_triggered();
	gbd->loadLevel(lvl);
	colors->setEnabled(true);
	colors->show();
}

void mainWindow::on_actionENew_triggered()
{
	beginEdit("*unnamed*");
}

void mainWindow::on_actionEOpen_triggered()
{
	QString file = getLevelFN();
	if (!file.isNull())
		beginEdit(QFileInfo(file).baseName());
}

void mainWindow::on_actionESave_triggered()
{
	gbd->saveLevel(false);
}

void mainWindow::on_actionESaveAs_triggered()
{
	gbd->saveLevel(true);
}

void mainWindow::on_actionEFinish_triggered()
{
	menu->setEnabled(true);
	actionESave->setEnabled(false);
	actionESaveAs->setEnabled(false);
	actionEFinish->setEnabled(false);
	gbd->setEditmode(false);
	on_actionStop_triggered();
	colors->setEnabled(false);
	colors->hide();
}

void mainWindow::onStop()
{
	actionPause->setEnabled(false);
	actionStop->setEnabled(false);
	blocks->clear();
	int lifes_c = lifes->text().mid(lifes->text().indexOf(':') + 1).toInt(); lifes->clear();
	int score_c = score->text().mid(score->text().indexOf(':') + 1).toInt(); score->clear();
	if (!cntn.isEmpty())
	{
		beginLevel(cntn, lifes_c, score_c);
		cntn = "";
	}
}

void mainWindow::addColor(QString clr)
{
	QAction *tmp = colors->addAction(gbd->getColouredIcon(clr), clr);
	connect(tmp, SIGNAL(triggered()), gbd, SLOT(changeDefColor()));
	connect(tmp, SIGNAL(triggered()), SLOT(setDefColor()));
}

void mainWindow::setDefColor(QString clr)
{
	foreach (QAction *itm, colors->actions())
	{
		QFont fnt = itm->font();
		if (itm->text() == clr)
			fnt.setBold(true);
		else
			fnt.setBold(false);
		itm->setFont(fnt);
	}
};


QStringList mainWindow::getCompleted()
{
	QStringList ret;
	QFile lvls(QDir::currentPath() + "/data.lvls");
	lvls.open(QIODevice::ReadOnly);
	QByteArray tmp = lvls.readAll();
	tmp = !tmp.isEmpty() ? qUncompress(tmp).trimmed() : tmp;
	QBuffer data(&tmp);
	data.open(QIODevice::ReadOnly);
	while (!data.atEnd())
		ret << data.readLine().trimmed();
	data.close();
	return ret;
}

void mainWindow::addCompleted(QString lvl)
{
	QStringList tmp = getCompleted();
	if (tmp.indexOf(lvl) != -1) return;
	tmp << lvl;
	QBuffer data;
	data.open(QIODevice::WriteOnly);
	foreach (QString itm, tmp)
		data.write(QString(itm + "\n").toAscii());
	data.close();
	QFile lvls(QDir::currentPath() + "/data.lvls");
	lvls.open(QIODevice::WriteOnly | QIODevice::Truncate);
	lvls.write(qCompress(data.data(), 9));
	lvls.close();
}

void mainWindow::win()
{
	QMessageBox::information(this, QString::fromUtf8("Победа!"), QString::fromUtf8("Поздравляем, Вы победили!"));
	if (campaign)
	{
		if (levels.indexOf(gbd->lvlName()) == levels.size() - 1)
		{
			QMessageBox::information(this, QString::fromUtf8("Победа!"), QString::fromUtf8("Поздравляем, Вы совсем победили! :)"));
			return;
		}
		addCompleted(levels[levels.indexOf(gbd->lvlName()) + 1]);
		createLevelsMenu();
		cntn = ":" + levels[levels.indexOf(gbd->lvlName()) + 1];
	}
}

void mainWindow::on_menuCont_triggered(QAction* action)
{
	campaign = true;
	beginLevel(":" + action->data().toString());
}

void mainWindow::createLevelsMenu()
{
	menuCont->clear();
	levels.clear();
	QStringList comp(getCompleted());
	QStringList allLevels = QStringList() << "Miniclip" << "Breakout" << "Jewels" << "Zen" << "Gee" << "Bricks";
	for (int i=0; i<allLevels.size(); i++)
	{
		levels << allLevels[i];
		QAction *tmp = menuCont->addAction(allLevels[i]);
		tmp->setData(allLevels[i]);
		if (comp.indexOf(allLevels[i]) != -1) continue;
		tmp->setEnabled(false);
	}
}

void mainWindow::on_actionHelp_triggered()
{
	static QProcess help;
	help.start("assistant", QStringList() << "-profile" << QDir::currentPath() + "/help/arcanoid.adp");
}
